package com.yeyks.common.utils;

import com.yeyks.common.config.CnBookingConfiguration;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * Aes CnBooking 加密解密 （Hex）
 *
 * @author: dagny
 * @date: 2019/9/26 0026 17:24
 */
public class AesUtil {

    public static String encrypt(String data, String key) {

        String ivString = CnBookingConfiguration.iv;
        //偏移量
        byte[] iv = ivString.getBytes();
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            int blockSize = cipher.getBlockSize();
            byte[] dataBytes = data.getBytes();
            int length = dataBytes.length;
            //计算需填充长度
            if (length % blockSize != 0) {
                length = length + (blockSize - (length % blockSize));
            }
            byte[] plaintext = new byte[length];
            //填充
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
            //设置偏移量参数
            IvParameterSpec ivSpec = new IvParameterSpec(iv);
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
            byte[] encryped = cipher.doFinal(plaintext);

            return parseByte2HexStr(encryped);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }

    public static String desEncrypt(String data) {

        String ivString = CnBookingConfiguration.iv;
        String key = CnBookingConfiguration.key;
        byte[] iv = ivString.getBytes();

        try {
            byte[] encrypt = parseHexStr2Byte(data);
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(iv);
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            byte[] original = cipher.doFinal(encrypt);
            return new String(original);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return null;
    }

    public static String parseByte2HexStr(byte[] buf) {
        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < buf.length; ++i) {
            String hex = Integer.toHexString(buf[i] & 255);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }

        return sb.toString();
    }

    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        } else {
            byte[] result = new byte[hexStr.length() / 2];

            for (int i = 0; i < hexStr.length() / 2; ++i) {
                int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
                int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
                result[i] = (byte) (high * 16 + low);
            }

            return result;
        }
    }

    public static void main(String[] args) {
        String data = "<DataSync><SyncType>3</SyncType><Data><Hotel HotelId=\"44907\" HotelStatus=\"\"></Hotel><Room RoomId=\"151663\" RoomStatus=\"\"></Room><RatePlans><RatePlan RatePlanId=\"1184\"><Rate RateId=\"86996\" Date=\"2016/1/14\" Price=\"80.00\" Currency=\"CNY\" Count=\"100\" Statu=\"026001\" LastCancelTime=\"2016/1/13\"></Rate><Rate RateId=\"86996\" Date=\"2016/1/15\" Price=\"80.00\" Currency=\"CNY\" Count=\"100\" Statu=\"026001\" LastCancelTime=\"2016/1/14\"></Rate></RatePlan></RatePlans><Order OrderId=\"\" OrderStatusId=\"\" Remark=\"\"></Order></Data></DataSync>";
        String encrypt = encrypt(data, CnBookingConfiguration.key);
        System.out.println("加密前：" + data);
        System.out.println("加密后：" + encrypt);
        String desEncrypt1 = desEncrypt(encrypt);
        System.out.println("解密后1：" + desEncrypt1);
        System.out.println("======================");


        String jiaMi = "0ad3773f966d9334a1d76a637c2d7d498dea2e88830443a60ff76a241ee752b12470b1898fed8e6473a7babef2565bd0902cf260dea098f2c9f4bce0240f567a123206474dcea72171a36c46b2ad6ef68ed769743f3e0c20c6a954235b6d010e17a9d682955f4c2f69eeb9d83be53cc3f651516eec7dae1c2df18d4edd47e88fb1a811ac3730c73b7b2abe93b54ee02ee9f272cc341887c07c30f5cc05a1ed03636b2b808b3a6d25767dc728ae699f57302f33794d665a95276832f300ee7c0989ae8df41c66e84b72ed1db5137b83a858d0880bd976692804dee34a062c87230e4f6d821a751c858931161ad4c8b6ac86b187c05c40c71920ccd798829c60d5722c475c724e463a412f594ea27967273ef4f02f52ec4158997f8b44039cd6651829c284cd85222b72f3f3d91a6a0990fe589b1219c1a764a1b75e09bb95af9fd9d0ac7f396f4f5648f3d657e2fb3e58ccb32404e17eb25184ee1a6a70be72892377d0503f4e4991d1f2f94630133d0d2ba2890cfe9a0608e04089f2aa38335f79086cb6b113dd1b70293ff2929102337eb57804ab2beb77b05667bf60c811932e395479cda51c51a2a4f49d44ad4ba1a77a26c150ea1d074b6430c3e60b93d2767db903e703ce67ca4adb07f729a0ac275725d186ebaa08412d5797a52ce7b4e7a53d9e4878a2557a454bb34240d075dc8f40f7c9f6e47687cafd317a8f24914b0d101446cae72925629d6c21086f569e22b83b2ef258c5330ab9a3eef9691fdfe1ee1c2c9481e48c974bc6d2e54d52";
        String desEncrypt2 = desEncrypt(jiaMi);
        System.out.println("2解密后2：" + desEncrypt2);
    }
}
